<?php


namespace App\Models\CacheModel;

use App\Models\CacheModel\lucky\AppUserAdornInfo;
use app\common\lib\Util;
use App\Models\Api\ArticleCollect;
use App\Models\Api\ArticleGood;
use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

/**
 * 女神动态模型
 * Class ZlGoddessSate
 * @package App\Models\CacheModel
 */
class ZlGoddessState extends BaseCache
{
    protected $table = 'wechatadmin.zl_goddess_state';

    public $cacheModel = 'goddesss_state.state';

    /**
     * 获取视频列表
     * @param $userInfo
     * @param int $aid
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function getGoddessStateIdsFromCache($userInfo, int $aid, int $limit = 10)
    {
        $page = input('page/d', 1);
        //获取所有视频id
        $ids = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, 1)
            ->setSort('desc')
            ->ZsGetIocData('list', function ()
            {
                return $this->getGoddessStateFromDms(1);
            });
        $array = array_flip($ids);//数组key value调换
        $index = $new_index = $array[$aid] ?? 0;//当前视频的下标
        $num = count($ids);
        //如果下标大于0，则重组数组，将当前视频之后的所有视频位置移动至数组头部
        if ($index)
        {
            $new_ids = [];
            for ($new_index; $new_index < $num; $new_index++)
            {
                $new_ids[] = $ids[$new_index];
            }
            for ($i = 0; $i < $index; $i++)
            {
                $new_ids[] = $ids[$i];
            }
            $video_ids = $new_ids;
        } else
        {
            $video_ids = $ids;
        }
        $data_list = getPaginatorData($num, $page);
        //获取分页后的数据
        $video_ids = array_slice($video_ids, $data_list['start'], $limit);
        unset($data_list['start'], $data_list['end']);
        $data = $this->batchGetInfoByIds($video_ids, ['id', 'type', 'url', 'duration', 'title', 'good_num', 'comment_num', 'collect_num', 'publish_time', 'introduction', 'content', 'thumb', 'thumb_width', 'thumb_height', 'url_des', 'is_recommend', 'read_num', 'read_base', 'author', 'author_type', 'avatar', 'a_id', 'target', 'link', 'mall_title', 'mall_img', 'mall_target', 'mall_link', 'author_type']);
        $data_list['data'] = $this->resetStateLIst($userInfo, $video_ids, $data);
        return $data_list;
    }

    /**
     * 缓存获取女神动态列表
     * @param $userInfo
     * @param int $type 类型 0=>全部 1=>视频,2=>语音,3=>文章
     * @param int $limit
     * @return array|mixed
     * @throws \Exception
     */
    public function getGoddessStateFromCache($userInfo, int $type = 0, int $limit = 10)
    {
        $page = input('page/d', 1);
        $ids = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $type)
            ->setSort('desc')
            ->ZsGetIocData('list', function () use ($type)
            {
                return $this->getGoddessStateFromDms($type);
            });
        $num = count($ids);
        $data_list = getPaginatorData($num, $page);
        //获取分页后的数据
        $ids = array_slice($ids, $data_list['start'], $limit);
        unset($data_list['start'], $data_list['end']);
        $data = $this->batchGetInfoByIds($ids, ['id', 'type', 'url', 'duration', 'title', 'good_num', 'comment_num', 'collect_num', 'publish_time', 'introduction', 'content', 'thumb', 'thumb_width', 'thumb_height', 'url_des', 'is_recommend', 'read_num', 'read_base', 'author', 'avatar', 'a_id', 'target', 'link', 'mall_title', 'mall_img', 'mall_target', 'mall_link', 'author_type']);
        $data_list['data'] = $this->resetStateLIst($userInfo, $ids, $data);
        return $data_list;
    }

    /**
     * 动态列表数据重组
     * @param $userInfo
     * @param array $ids
     * @param array $goddessStateDatas
     * @return array
     * @throws \Exception
     */
    public function resetStateLIst($userInfo, array $ids, array $goddessStateDatas)
    {
        // 组合数据 并排序
        $resData = [];
        //获取用户已点赞的数据
        $goddessGood = $userInfo['id'] ? (new ArticleGood())->getGoodFromCache($userInfo['id'], 2) : [];
        // 获取用户收藏话题ids
        $collectIds = $userInfo['id'] ? array_keys((new ArticleCollect())->getUserAllCollectFromCache($userInfo['id'], 2)) : [];
        $oldArticleArr = [];
        $reads = [];
        if ($userInfo && isset($userInfo['id']) && $userInfo['id'])
        {
            $reads = (new ArticleRead())->getUserArticleReadIds($userInfo['id'], 1);
        }
        foreach ($ids as $idItem)
        {
            $link = null;
            $goodNum = (int)(($goddessStateDatas[$idItem]['good_num'] ?? 0) + floor(((($goddessStateDatas[$idItem]['read_num'] ?? 0) + ($goddessStateDatas[$idItem]['read_base'] ?? 0)) / 30)));
            $adInfo = null;
            if (isset($goddessStateDatas[$idItem]['mall_title'], $goddessStateDatas[$idItem]['mall_img'], $goddessStateDatas[$idItem]['mall_target'], $goddessStateDatas[$idItem]['mall_link']) && $goddessStateDatas[$idItem]['mall_title'] && $goddessStateDatas[$idItem]['mall_img'] && $goddessStateDatas[$idItem]['mall_target'] && $goddessStateDatas[$idItem]['mall_link'])
            {
                $adInfo = [
                    'img' => $goddessStateDatas[$idItem]['mall_img'],
                    'title' => $goddessStateDatas[$idItem]['mall_title'],
                    'target' => $goddessStateDatas[$idItem]['mall_target'],
                    'link' => $goddessStateDatas[$idItem]['mall_link'] . '&umeng_event_name=common_target_link&umeng_event_label=' . urlencode('视频关联-' . $goddessStateDatas[$idItem]['mall_target'] . '-' . $goddessStateDatas[$idItem]['mall_link'])
                ];
            }
//            // 作者类型 1=>官方,2=>女神
            $authorType = (int)($goddessStateDatas[$idItem]['author_type'] ?? 0);
            $adorn = (new AppUserAdornInfo())->getUserAdornInfo(0, $authorType ?: 3);//3=>用户来稿标签
            $isRead = 0;
            if ((int)$goddessStateDatas[$idItem]['type'] === 6)
            {
                $ur = parse_url($goddessStateDatas[$idItem]['link']);

                $que = $ur['query'] ?? '';
                if ($que)
                {
                    $arr = convertUrlQuery($que);
                    $id = (int)($arr['id'] ?? $goddessStateDatas[$idItem]['id']);

                    $articleInfo = current((new Article())->batchGetInfo([$id], ['read', 'read_base']));

                    $readNum = ($articleInfo['read'] ?? 0) + ($articleInfo['read_base'] ?? 0);

                    if (in_array($id, $reads, false))
                    {
                        $isRead = 1;
                    }
                } else
                {
                    $id = (int)$goddessStateDatas[$idItem]['id'];

                    $readNum = ($goddessStateDatas[$idItem]['read_num'] ?? 0) + ($goddessStateDatas[$idItem]['read_base'] ?? 0);
                }

            } else
            {
                $id = (int)$goddessStateDatas[$idItem]['id'];

                $readNum = ($goddessStateDatas[$idItem]['read_num'] ?? 0) + ($goddessStateDatas[$idItem]['read_base'] ?? 0);

                if ((int)$goddessStateDatas[$idItem]['type'] === 1)
                {
                    $target = 'local';
                    $link = "article_info?id={$id}&type=2&content_type=1&need_auth=0";
                }
            }

            $resData[$idItem] = [
                'id' => $id,
                'type' => (int)$goddessStateDatas[$idItem]['type'],
                'thumb' => htmlspecialchars_decode($goddessStateDatas[$idItem]['thumb']),
                'thumb_width' => (int)$goddessStateDatas[$idItem]['thumb_width'],
                'thumb_height' => (int)$goddessStateDatas[$idItem]['thumb_height'],
                'url' => htmlspecialchars_decode($goddessStateDatas[$idItem]['url']),
                'title' => $goddessStateDatas[$idItem]['title'],
                'time' => Util::timeToStr($goddessStateDatas[$idItem]['publish_time']),
                'release_time' => date('Y-m-d H:i:s', $goddessStateDatas[$idItem]['publish_time']),
                'good_num' => $goodNum < 0 ? 0 : $goodNum,
                'comment_num' => (int)($goddessStateDatas[$idItem]['comment_num'] < 0 ? 0 : $goddessStateDatas[$idItem]['comment_num']),
                'collect_num' => (int)($goddessStateDatas[$idItem]['collect_num'] < 0 ? 0 : $goddessStateDatas[$idItem]['collect_num']),
                'is_good' => in_array($goddessStateDatas[$idItem]['id'], $goddessGood) ? 1 : 0,
                'is_collect' => in_array($goddessStateDatas[$idItem]['id'], $collectIds) ? 1 : 0,
                'duration' => (int)$goddessStateDatas[$idItem]['duration'],
                'introduction' => $goddessStateDatas[$idItem]['introduction'],
                'target' => $target ?? $goddessStateDatas[$idItem]['target'],
                'link' => $link ?? $goddessStateDatas[$idItem]['link'],
                'author' => $goddessStateDatas[$idItem]['author'],
                'avatar' => $goddessStateDatas[$idItem]['avatar'],
                'a_id' => $goddessStateDatas[$idItem]['a_id'],
                'ad_info' => $adInfo,
                'data_type' => 1,// 1=>动态，2=>广告
                'author_type' => $authorType,
                'avatar_adorn' => $adorn['adorn_info']['reality_img'],
                'tag' => $adorn['tag_info']['reality_img'],
                'read_num' => $readNum,
                'is_read' => $isRead
            ];
            //若当前文章跳转至旧版星文则获取旧版星文id
            if ($goddessStateDatas[$idItem]['type'] == 6)
            {
                //link处理成url和param
                $url = parse_url($goddessStateDatas[$idItem]['link']);
                if (isset($url['query']))
                {
                    //获取url请求参数
                    $url_query = convertUrlQuery($url['query']);
                    if (isset($url_query['id']) && $url_query['id'])
                    {
                        $oldArticleArr[$idItem] = $url_query['id'];
                    }
                }
            }
        }

        //若type为6，则获取旧版星文评论数和点赞数
        if ($oldArticleArr)
        {
            //获取用户已点赞的数据
            $articleGood = $userInfo['id'] ? (new ArticleGood())->getGoodFromCache($userInfo['id'], 1) : [];
            //获取旧版星文评论数和点赞数
            $oldArticleInfo = (new Article())->batchGetInfo(array_values($oldArticleArr), ['comment', 'good', 'read', 'read_base']);
            //重组动态列表数据
            foreach ($oldArticleArr as $key => $item)
            {
                $goodNum = (int)(($oldArticleInfo[$item]['good'] ?? 0) + floor(((($oldArticleInfo[$item]['read'] ?? 0) + ($oldArticleInfo[$item]['read_base'] ?? 0)) / 30)));
                if (isset($oldArticleInfo[$item]))
                {
                    $resData[$key]['comment_num'] = (int)$oldArticleInfo[$item]['comment'];
                    $resData[$key]['good_num'] = (int)$goodNum;
                    $resData[$key]['is_good'] = in_array($item, $articleGood) ? 1 : 0;
                }
            }
        }
        return $resData ? array_values($resData) : [];
    }

    /**
     * 数据库获取女神动态列表
     * @param int $type 类型 0=>全部 1=>视频,2=>语音,3=>文章
     * @return array
     */
    public function getGoddessStateFromDms(int $type = 0)
    {
        //类型 1=》图文（可分享），2=》竖屏视频，3=》横屏视屏，4=》音频,6=》获取旧版星闻
        switch ($type)

        {
            case 1://视频
                $where = ['status' => 1, 'type' => ['in', [2, 3]]];
                break;
            case 2://语音
                $where = ['status' => 1, 'type' => 4];
                break;
            case 3://文章
                $where = ['status' => 1, 'type' => ['in', [1, 6]]];
                break;
            default:
                $where = ['status' => 1];
                break;
        }
        $where['publish_time'] = ['<', time()];
        try
        {
            $data = $this->where($where)->order('id', 'desc')->column('publish_time,sort', 'id');
            $ids = [];
            foreach ($data as $id => $datum)
            {
                $ids[$id] = (float)($datum['sort'] . '.' . $datum['publish_time']);
            }
            arsort($ids);
            return $ids;
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 批量从数据库获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        $ids = is_array($ids) ? $ids : explode(',', $ids);
        $field = 's.id,s.aid,s.type,s.url,s.duration,s.title,s.good_num,s.collect_num,s.comment_num,s.publish_time,s.introduction,s.content,s.status,s.thumb,s.thumb_width,s.thumb_height,s.is_top,s.is_hot,s.sort,s.create_time,s.url_des,s.is_recommend,au.uid a_id,au.name author,au.type author_type,au.thumb avatar,s.read_num,s.read_base,s.target,s.link,s.mall_title,s.mall_img,s.mall_target,s.mall_link';
        try
        {
            $data = $this
                ->alias('s')
                ->join('wechatadmin.zhunle_article_author au', 's.aid=au.id')
                ->where(['s.id' => ['in', $ids]])
                ->column($field, 's.id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }
}
